﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Weber.CS3280.Interfaces;
using Weber.CS3280.Inventory.Logic;
using Weber.CS3280.Inventory.UI.Controls;
using Weber.CS3280.Inventory.UI.Windows;
using Weber.CS3280.UI.ViewModels;

namespace Weber.CS3280.Inventory.UI.ViewModels
{
	public class InventoryListViewModel : ListingViewModelBase, ICustomCleanup
	{
		private InventoryItemViewModel[] _inventoryItems = new InventoryItemViewModel[0];
		private ItemCategoryListViewModel _categoriesList;

		public InventoryListViewModel()
		{
			WindowTitle = "Inventory Listing";
			_categoriesList = new ItemCategoryListViewModel();
			_categoriesList.RefreshViewCommand.Execute(null);

			Lookstone.Data.DataEvent.AddChangeEventHandler(OnDataChanged);
		}

		void _inventory_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "Items")
				RefreshView();
		}

		private void OnDataChanged(object sender, Lookstone.Data.DataEvent.DataChangeEventArgs e)
		{
			// If an item is changed, refresh the list of items
			if (e.EventObject is Data.InventoryItem)
				RefreshView();
		}

		/// <summary>
		/// Triggered from the base class's ExecuteAddCommand
		/// </summary>
		/// <param name="sender">Reference of the Control that is triggering the action</param>
		protected override void AddItem(Control sender)
		{
			// Create a new window that displays the InventoryDetails
			InventoryItemViewModel viewModel = new InventoryItemViewModel(_categoriesList);

			// Get a reference to the Window that contained the sender Control
			Window window = Window.GetWindow(sender);

			// New records work fine with Modeless, because the InventoryList knows when an item is added or removed.
			EditControlHostWindow.ShowWindow<InventoryItemDetailsControl>(viewModel, window);
		}

		/// <summary>
		///  Gets an Array of InventoryItemViewModel objects
		/// </summary>
		/// <returns>Array of InventoryItemViewModel objects</returns>
		protected override ViewModelBase[] GetItems()
		{
			using (Data.InventoryConnectionContext context = new Data.InventoryConnectionContext())
			{
				_inventoryItems = InventoryItemController.GetItems(context)
					.Select(item => new InventoryItemViewModel(_categoriesList, item))
					.ToArray();

				return _inventoryItems;
			}
		}

		public override void DoCleanup()
		{
			foreach (InventoryItemViewModel inventoryItem in _inventoryItems)
				inventoryItem.DoCleanup();
		}
	}
}
